const mysql = require('mysql2/promise');

class Database {
  constructor(config) {

    config= {
      host: 'localhost',  
      user: 'root',  
      password: 'root',  
      database: 'test',
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0,
      timezone: '+08:00',
      charset: 'utf8mb4' // 设置字符集为UTF-8

    };
    this.pool = mysql.createPool(config);
  }

  async query(sql, params) {
    const connection = await this.pool.getConnection();

    try {
      const [rows, fields] = await connection.execute(sql, params);
      return rows;
    } finally {
      connection.release();
    }
  }

// 封装执行方法
async  execute(sql, values) {
  let connection;
  try {
    connection = await this.pool.getConnection();
    const [results, fields] = await connection.execute(sql, values);
    return results;
  } catch (error) {
    throw error;
  } finally {
    if (connection) connection.release(); // 释放连接
  }
}
  
  async close() {
    await this.pool.end();
  }
}

module.exports = Database;
